package com.alumni_circle.core.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alumni_circle.core.utils.GetOpen;
import com.alumni_circle.entity.security.UserSecurity;
import com.alumni_circle.mapper.security.UserSecurityMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


/**
 * @author  龙小虬
 * @create  2020-08-02 00:36
 *
 * From 表单形式登录
 *
 * 参数处理验过滤器（针对ajax、表单等请求） 1.获取请求参数； 2.对获取到的请求参数进行处理（解密、字符串替、请求参数分类截取等等）； 3.把处理后的参数放回到请求列表里面
 **/
public class FormLoginFilter implements Filter {

    @Resource
    UserSecurityMapper userSecurityMapper;
    /**
     * 需要过滤的地址
     */
    private static List<String> urlList = Arrays.asList("/login");

    /**
     * 是否不需要过滤
     *
     * @param requestUrl
     *            请求的url
     * @return
     */
    private boolean isPast(String requestUrl) {
        for (String url : urlList) {
            if (requestUrl.equals(url)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        System.out.println(("过滤器2执行开始"));
        String url = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest)request).getContextPath().length());

        //通过地址对特定的请求进行处理，如果不需要可以不用，如果不用，就会对使用的请求进行过滤
        if (isPast(url)) {
            MyHttpServletRequestWrapper requestWrapper = new MyHttpServletRequestWrapper(
                    (HttpServletRequest) request);
            // 1.获取需要处理的参数
            String username = requestWrapper.getParameter("username");
            String password = requestWrapper.getParameter("password");

            // 2.更改数据，登录时判断登录名是否为WeChat，若是，则修改传输的请求数据
            if("WeChat".equals(username)){
                String open = GetOpen.sendGet(password);
                if(!"errcode".equals(open)){
                    QueryWrapper<UserSecurity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("openid",open);
                    UserSecurity userSecurity = userSecurityMapper.selectOne(queryWrapper);
                    if(!ObjectUtil.hasEmpty(userSecurity)) {
                        requestWrapper.setParameter("username",userSecurity.getUsername());
                        requestWrapper.setParameter("password",userSecurity.getPassword());
                    }
                }
            }
            // 3.放行，把我们的requestWrapper放到方法当中
            chain.doFilter(requestWrapper, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}

